<?php
if(!defined('IN_DISCUZ')) {
    exit('Access Denied');
}

class plugin_erling_grid_ad {
    private $configs = [];
    private $has_permission = false;

    private function get_configs() {
        $keys = [
            'allowed_groups','grid_columns', 'grid_rows', 'title_length', 
            'empty_text', 'form_tip', 'contact_info', 'default_color',
            'default_bgcolor', 'daily_credit', 'monthly_credit',
            'bgcolor_on', 'use_nofollow', 'cache_time','credit_recharge_url'
        ];
        
        $configs = C::t('#erling_grid_ad#configs')->fetch_by_keys($keys);
        
        return [
            'allowed_groups' => $configs['allowed_groups']['value']?? [],
            'grid_columns' => $configs['grid_columns']['value'] ?? 3,
            'grid_rows' => $configs['grid_rows']['value'] ?? 3,
            'title_length' => $configs['title_length']['value']?? 10,
            'empty_text' => $configs['empty_text']['value'] ?? '广告位招租中',
            'form_tip' => $configs['form_tip']['value']?? '',
            'contact_info' => $configs['contact_info']['value']?? '',
            'default_color' => $configs['default_color']['value'] ?? '#333333',
            'default_bgcolor' => $configs['default_bgcolor']['value'] ?? '#FFFFFF',
            'daily_credit' => $configs['daily_credit']['value'] ?? 0,
            'monthly_credit' => $configs['monthly_credit']['value'] ?? 0,
            'bgcolor_on' => $configs['bgcolor_on']['value'] ?? 0,
            'use_nofollow' => $configs['use_nofollow']['value'] ?? 0,
            'cache_time' => $configs['cache_time']['value']?? 0,
            'credit_recharge_url' => $configs['credit_recharge_url']['value']?? '',
        ];
    }

    private function get_current_user_groups() {
        global $_G;
        $groups = array();
        
        // 获取主用户组
        if (!empty($_G['groupid'])) {
            $groups[] = $_G['groupid'];
        }
        
        // 获取扩展用户组
        if (!empty($_G['member']['extgroupids'])) {
            $extgroups = explode(',', $_G['member']['extgroupids']);
            $groups = array_merge($groups, $extgroups);
        }
        
        return $groups;
    }
    
    public function __construct() {
        $this->configs = $this->get_configs();
        $allowed_groups = unserialize($this->configs['allowed_groups']);
        $user_groups = $this->get_current_user_groups();
        $this->has_permission = in_array(1, $user_groups) || !empty(array_intersect($allowed_groups, $user_groups));
    }
    public function global_header() {
        global $_G;
        // $_var['grid_items'] = $grid_items;
        // $_var['grid_columns'] = $grid_columns;
        // $_var['grid_rows'] = $grid_rows;
        $position = 2;
        $configs = $this->configs;
        
        $result = C::t('#erling_grid_ad#ad')->fetch_all(1, 100, [
            'status' => '',
            'position' => 2,
        ]);
        $header_ads = $result['data'];

        // $cache_key = 'erling_grid_ad_header_ads';
        
        // if (!empty($configs['cache_time']) && $configs['cache_time'] > 0) {
        //     $header_ads = memory('get', $cache_key);
        // }

        // if (empty($header_ads)) {
        //     $result = C::t('#erling_grid_ad#ad')->fetch_all(1, 100, [
        //         'status' => '',
        //         'position' => 2,
        //     ]);
        //     $header_ads = $result['data'];
            
        //     if (!empty($header_ads)) {
        //         memory('set', $cache_key, $header_ads, $configs['cache_time']);
        //     }
        // }

        // 处理网格数据
        $grid_items = array();
        $total_slots = $configs['grid_columns'] * $configs['grid_rows'];
        for ($i = 1; $i <= $total_slots; $i++) {
            $row = ceil($i / $configs['grid_columns']);
            $col = $i % $configs['grid_columns'];
            $col = $col == 0 ? $configs['grid_columns'] : $col;
            $grid_items[$i] = array(
                'ad' => null,
                'grid_row' => $row,
                'grid_col' => $col,
            );
        }
        
        foreach ($header_ads as $ad) {
            $sort = intval($ad['sort']);
            if (isset($grid_items[$sort])) {
                if ($ad['status'] != 1) {
                    $ad['title'] = '已售-审核中';
                    $ad['url'] = '';
                    $ad['bgcolor'] = $configs['default_bgcolor'];
                    $ad['color'] = $configs['default_color'];
                    $ad['bold'] = 0;
                    $ad['underline'] = 0;
                    $ad['italic'] = 0;
                }

                $max_length = $configs['title_length'];
                $title = $ad['title'];
                $length = 0;
                $new_title = '';
                
                for ($i = 0; $i < mb_strlen($title); $i++) {
                    $char = mb_substr($title, $i, 1);
                    // 英文字符按0.5计算，中文字符按1计算
                    $char_width = preg_match('/[a-zA-Z0-9\.,;:\'\"!?]/', $char) ? 0.5 : 1;
                    
                    if ($length + $char_width > $max_length) {
                        break;
                    }
                    
                    $new_title .= $char;
                    $length += $char_width;
                }
                
                if ($length > 0) {
                    $ad['title'] = $new_title;
                }

                $grid_items[$sort]['ad'] = $ad;
            }
        }
        
        $ad_html = '';
        ob_start();

        include template('erling_grid_ad:ad_display');
        $ad_html = ob_get_contents();
        ob_end_clean();

        $ad_html = str_replace('</script>', 'window.has_permission = '.(int)$this->has_permission.';</script>', $ad_html);

        return $ad_html;
    }
    
    
}